<?php

namespace App\Models\Posts;

use App\Jobs\Posts\AddPostCommentManuakJob;
use App\Models\User\WxUser;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class WxPostsCommentManual extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'wx_posts_comment_manual';
    public $timestamps = false;

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // 在模型创建之前触发的操作
            global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
            if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                throw new \Exception('权限不足，人工评论只允许超级管理员增加');
            }
        });

        static::created(function ($model) {
            Cache::put('posts_comment_manual_last_post_id', $model->posts_id);

            $maxExpectTime = Carbon::parse($model->expect_time);
            // 计算与当前时间的差异（分钟数）
            $now = Carbon::now();
            $diffInMinutes = $now->diffInMinutes($maxExpectTime, false); // 第二个参数false表示计算时区差异

            // 如果是负数，表示在当前时间之前，则返回0
            if ($diffInMinutes < 0) {
                $diffInMinutes = 0;
            }
            AddPostCommentManuakJob::dispatch($model->id)->delay(now()->addMinutes($diffInMinutes));

        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'status'){

                }
            }
        });
        static::deleted(function ($model) {

        });
        // 其他的模型事件监听...
    }

    public function ower()
    {
        return $this->hasOne(WxUser::class, 'id', 'expect_user');
    }

}
